﻿/*
------------------------------------------------------------------------------
This source file is a part of Flexible Localization.

Copyright (c) 2011 - 2012 Florian Haag

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------
 */
using System;
using System.Collections.Generic;

using Gtk;

using TwoLayeredGUI.FlowView;
using TwoLayeredGUI.Gtk.FlowView;
using TwoLayeredGUI.Samples.SampleCore;

namespace TwoLayeredGUI.Samples.SampleGtkSharpFrontend
{
	partial class MainWindow
	{
		private readonly EventBox flowEventArea = new EventBox() {
			Events = Gdk.EventMask.AllEventsMask
		};
		
		private readonly DrawingArea flowArea = new DrawingArea();
		
		private void InitializeFlowView()
		{
			flowArea.SizeAllocated += delegate(object o, SizeAllocatedArgs args) {
				UpdateFlowItems();
			};
			flowArea.ExposeEvent += delegate(object o, ExposeEventArgs args) {
				using (var backGC = new Gdk.GC(args.Event.Window)) {
					backGC.RgbFgColor = new Gdk.Color(255, 255, 255);
					args.Event.Window.DrawRectangle(backGC, true, flowArea.Allocation.Left, flowArea.Allocation.Top, flowArea.Allocation.Width, flowArea.Allocation.Height);
				}
				
				if (flowItemsWithPositions != null) {
					DrawFlowItems(flowItemsWithPositions, this, args.Event.Window, new Gdk.Point(0, 0));
				}
			};
			
			flowEventArea.LeaveNotifyEvent += delegate(object o, LeaveNotifyEventArgs args) {
				if (selectedItem != null) {
					selectedItem = null;
					flowArea.QueueDraw();
				}
			};
			flowEventArea.MotionNotifyEvent += delegate(object o, MotionNotifyEventArgs args) {
				bool selChanged = false;
				foreach (var item in flowItemsWithPositions) {
					if (item.GetCompleteRectangle().Contains(new Gdk.Point(Convert.ToInt32(args.Event.X), Convert.ToInt32(args.Event.Y)))) {
						if (item != selectedItem) {
							selectedItem = item;
							selChanged = true;
						}
						break;
					}
				}
				if (selChanged) {
					flowArea.QueueDraw();
				}
			};
			
			RefreshFlowItems();
		}
		
		private class FlowSizeProvider : IFlowSizeProvider<Example.FlowItem>
		{
			public FlowSizeProvider(Pango.Context context, FlowManager<Example.FlowItem> flowManager)
			{
				if (context == null) {
					throw new ArgumentNullException("context");
				}
				if (flowManager == null) {
					throw new ArgumentNullException("flowManager");
				}
				
				this.context = context;
				this.flowManager = flowManager;
			}
			
			private readonly Pango.Context context;
			
			private readonly FlowManager<Example.FlowItem> flowManager;
			
			private Pango.Layout textLayout;
			
			private int textLineHeight;
			
			public void BeginMeasuring()
			{
				textLayout = new Pango.Layout(context);
				textLayout.FontDescription = context.FontDescription;
				textLayout.SetText("Gg");
				
				int w;
				textLayout.GetPixelSize(out w, out textLineHeight);
			}
			
			public void EndMeasuring()
			{
				textLayout.Dispose();
				textLayout = null;
			}
			
			public double GetItemMinLength(Example.FlowItem item, int firstPart, int lastPart)
			{
				int result = 4;
				for (int i = firstPart; i <= lastPart; i++) {
					result += item[i].Width;
				}
				if (flowManager.Orientation == FlowOrientation.Vertical) {
					result += textLineHeight;
				}
				return result;
			}
			
			public double GetItemMinSizeInLine(Example.FlowItem item, int firstPart, int lastPart)
			{
				int result = 4;
				for (int i = firstPart; i <= lastPart; i++) {
					result = Math.Max(result, item[i].Height);
				}
				if (flowManager.Orientation == FlowOrientation.Horizontal) {
					result += textLineHeight;
				}
				return result;
			}
		}
		
		private void DrawFlowItems(IEnumerable<FlowItemWithPosition<Example.FlowItem>> items, Widget widget, Gdk.Drawable drawable, Gdk.Point offset)
		{
			var itemGC = new Gdk.GC(drawable) {
				RgbFgColor = new Gdk.Color(255, 255, 0)
			};
			var selectedItemGC = new Gdk.GC(drawable) {
				RgbFgColor = new Gdk.Color(0, 255, 0)
			};
			var forceWrapGC = new Gdk.GC(drawable) {
				RgbFgColor = new Gdk.Color(80, 80, 80)
			};
			var evenPartGC = new Gdk.GC(drawable) {
				RgbFgColor = new Gdk.Color(0, 0, 255)
			};
			var oddPartGC = new Gdk.GC(drawable) {
				RgbFgColor = new Gdk.Color(140, 140, 255)
			};
			var textGC = new Gdk.GC(drawable) {
				RgbFgColor = new Gdk.Color(60, 60, 60)
			};
			var blueGC = new Gdk.GC(drawable) {
				RgbFgColor = new Gdk.Color(0, 0, 128)
			};
			var redGC = new Gdk.GC(drawable) {
				RgbFgColor = new Gdk.Color(255, 0, 0)
			};
			try {
				int textHeight;
				using (var layout = new Pango.Layout(widget.PangoContext)) {
					layout.FontDescription = widget.PangoContext.FontDescription;
					layout.SetText("Gg");
					int w;
					layout.GetPixelSize(out w, out textHeight);
					
					foreach (var item in items) {
						bool isSelected = item == selectedItem;
						var rect = item.GetRectangle();
						rect.Offset(widget.Allocation.X, widget.Allocation.Y);
						rect.Offset(offset);
						
						drawable.DrawRectangle(isSelected ? selectedItemGC : itemGC, true, rect);
						if (item.Item.Item.ForceLineBreakBefore && (item.Item.FirstPart == 0)) {
							if (flowManager.Orientation == FlowOrientation.Horizontal) {
								drawable.DrawRectangle(forceWrapGC, true, rect.Left, rect.Top, 3, rect.Height);
							} else {
								drawable.DrawRectangle(forceWrapGC, true, rect.Left, rect.Top, rect.Width, 3);
							}
						}
						if (item.Item.Item.ForceLineBreakAfter && (item.Item.LastPart == item.Item.Item.PartCount - 1)) {
							if (flowManager.Orientation == FlowOrientation.Horizontal) {
								drawable.DrawRectangle(forceWrapGC, true, rect.Right - 3, rect.Top, 3, rect.Height);
							} else {
								drawable.DrawRectangle(forceWrapGC, true, rect.Left, rect.Bottom - 3, rect.Width, 3);
							}
						}
						layout.SetText(item.Item.Item.Index.ToString());
						drawable.DrawLayout(textGC, rect.Left + 1, rect.Top + 1, layout);
						
						int itemLineProgress;
						if (flowManager.Orientation == FlowOrientation.Horizontal) {
							itemLineProgress = rect.Left + 2;
						} else {
							itemLineProgress = rect.Top + 2 + textHeight;
						}
						for (int p = item.Item.FirstPart; p <= item.Item.LastPart; p++) {
							var partSz = item.Item.Item[p];
							if (flowManager.Orientation == FlowOrientation.Horizontal) {
								drawable.DrawRectangle(p % 2 == 0 ? evenPartGC : oddPartGC, true,
								                       itemLineProgress, rect.Top + 2 + textHeight, partSz.Width, partSz.Height);
							} else {
								drawable.DrawRectangle(p % 2 == 0 ? evenPartGC : oddPartGC, true,
								                       rect.Left + 2, itemLineProgress, partSz.Height, partSz.Width);
							}
							itemLineProgress += partSz.Width;
						}
						
						if (isSelected) {
							drawable.DrawRectangle(blueGC, false, item.GetBeforeRectangle());
							drawable.DrawRectangle(redGC, false, item.GetAfterRectangle());
						}
					}
				}
			}
			finally {
				itemGC.Dispose();
				selectedItemGC.Dispose();
				forceWrapGC.Dispose();
				evenPartGC.Dispose();
				oddPartGC.Dispose();
				textGC.Dispose();
			}
		}
		
		private readonly FlowManager<Example.FlowItem> flowManager = new FlowManager<Example.FlowItem>() {
			ItemSpacing = 2,
			LineSpacing = 3
		};
		
		private Example.FlowItem[] flowItems;
		
		private FlowItemWithPosition<Example.FlowItem>[] flowItemsWithPositions;
		
		private FlowItemWithPosition<Example.FlowItem> selectedItem;
		
		private void RefreshFlowItems()
		{
			flowItems = Example.CreateRandomFlowItems();
			flowItemsWithPositions = null;
			UpdateFlowItems();
		}
		
		private void UpdateFlowItems()
		{
			if (flowItems != null) {
				flowItemsWithPositions = flowManager.PlaceItems((flowManager.Orientation == FlowOrientation.Horizontal ? flowArea.Allocation.Width : flowArea.Allocation.Height) - 1,
				                                                new FlowSizeProvider(flowArea.PangoContext, flowManager),
				                                                flowItems);
				flowArea.QueueDraw();
			}
		}
		
		private void RbAlignmentChanged(object o, EventArgs args)
		{
			if (rbStart.Active) {
				flowManager.Alignment = FlowAlignment.Start;
			} else if (rbCenter.Active) {
				flowManager.Alignment = FlowAlignment.Center;
			} else if (rbEnd.Active) {
				flowManager.Alignment = FlowAlignment.End;
			}
			UpdateFlowItems();
		}
		
		private RadioButton rbStart;
		
		private RadioButton rbCenter;
		
		private RadioButton rbEnd;
		
		private readonly VBox flowSettingsPane = new VBox(false, 4);
		
		private readonly Table pFlowView = new Table(3, 2, false);
		
		private void SetFlowLayoutPaned(Paned paned)
		{
			if (paned == null) {
				throw new ArgumentNullException("paned");
			}
			
			int position = 150;
			
			if (this.flowPaned != null) {
				position = this.flowPaned.Position;
				
				pFlowView.Remove(this.flowPaned);
				this.flowPaned.Remove(flowEventArea);
				this.flowPaned.Remove(flowSettingsPane);
				this.flowPaned.Dispose();
			}
			
			this.flowPaned = paned;
			
			paned.Add1(flowEventArea);
			paned.Add2(flowSettingsPane);
			
			paned.Position = position;
			
			pFlowView.Attach(paned, 0, 2, 1, 2, AttachOptions.Fill | AttachOptions.Expand, AttachOptions.Fill | AttachOptions.Expand, 0, 0);
			
			pFlowView.ShowAll();
		}
		
		private Paned flowPaned;
		
		private RadioButton rbFlowHorizontally;
		
		private RadioButton rbFlowVertically;
		
		private void RbFlowHVToggled(object sender, EventArgs args)
		{
			if (rbFlowHorizontally.Active) {
				SetFlowLayoutPaned(new HPaned());
				flowManager.Orientation = FlowOrientation.Horizontal;
			} else {
				SetFlowLayoutPaned(new VPaned());
				flowManager.Orientation = FlowOrientation.Vertical;
			}
			UpdateFlowItems();
		}
	}
}
